<template>
  <div ref="imageWrapper">
    <a-card title="查询条件" class="search">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form-model ref="ruleForm" :model="queryParam" :rules="rules" layout="inline" @keyup.enter.native="onSearch">
          <a-row :gutter="24">
            <a-col :md="6" :sm="8">
              <a-form-model-item label="项目名称" prop="proName">
                <a-input @click.native="openOrganModel" readOnly v-model="queryParam.proName" placeholder="请选择" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="8" :offset="12">
              <span style="float: right" class="table-page-search-submitButtons">
                <a-button type="primary" @click="onSearch" icon="search" class="yellow_search_btn">查询</a-button>
                <a-button class="clear_btn" type="text" @click="searchReset" icon="reload">清除条件</a-button>
                <a-button
                  type="danger"
                  :loading="ydLoading"
                  @click="handleToYD()"
                  icon="arrow-right"
                  style="margin-left: 18px"
                  >转疑点</a-button
                >
                <!-- <a-button v-if="isBackButton" type="primary" style="margin-left: 8px" @click="backUppage">
                  返回
                </a-button> -->
              </span>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>
    <!-- v-if="dataSource == []" -->
    <a-card style="margin-top: 20px">
      <a-row :gutter="24">
        <a-col :span="6" class="right-tree">
          <a-table
            size="middle"
            rowKey="id"
            :dataSource="treeDataSource"
            :columns="columns1"
            :pagination="false"
            :loading="treeLoading"
            class="antableClass"
            :expanded-row-keys.sync="expandedRowKeys"
            :row-selection="{ type: 'radio', selectedRowKeys: treeRowKeys, onChange: onSelectChange }"
          >
          </a-table>
        </a-col>
        <a-col :span="18">
          <a-table
            :columns="columns2"
            :dataSource="dataSource"
            size="middle"
            rowKey="id"
            :pagination="ipagination"
            :loading="loading"
            @change="handleTableChange"
            class="antableClass"
            :scroll="{ x: 1800 }"
            :row-selection="rowSelectionlist"
          >
            <template v-slot:unitName="text">
              <j-ellipsis :length="10" :value="text" />
            </template>
            <template v-slot:proName="text">
              <j-ellipsis :length="10" :value="text" />
            </template>
            <span slot="action" slot-scope="text, record">
              <a v-if="record.unitName !== '合计'" @click="handleCheckDetail(record)">详情</a>
            </span>
          </a-table>
        </a-col>
      </a-row>
    </a-card>
    <CheckOrganModal ref="departModal" @getdata="updateQueryParam"></CheckOrganModal>
    <YDModel ref="YDModel" :routerData="$route.path" />
    <CheckAndEditModel ref="modalForm" @ok="updateProList"></CheckAndEditModel>
  </div>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { YzzxListMixin } from '../../../sjxmzygl/yzzx/mixins/YzzxListMixin'
import CheckOrganModal from './CheckOrganModal'
import { base64toImg } from '@/mixins/base64toImg'
import YDModel from '@/views/sj/components/YDModel'
import { getAction, postAction } from '@/api/manage'
import jumpConfigMixin from '@/views/sj/sjxmzygl/sjxmss/jumpConfigMixin'
import { columns1, columns2 } from './columns'
import { filterObj } from '@/utils/util'
import CheckAndEditModel from './ModalView/CheckAndEditModel'
export default {
  name: 'ye1',
  mixins: [JeecgListMixin, YzzxListMixin, base64toImg, jumpConfigMixin],
  components: { CheckOrganModal, YDModel,CheckAndEditModel},
  data() {
    return {
      queryParam: {
        proName: ''
      },
      isBackButton: false,
      superParam: {
        id: '756be7d7fb510292cce689b3606c932d',
        modelId: '756be7d7fb510292cce689b3606c932d',
        extraFlag: true
      },
      disableMixinCreated: true,
      columns1: columns1(this),
      columns2: columns2(this),
      url: {
        treelist: '/sjmx/queryMoreSuject',
        list: '/sjmx/querySubjectExpend',
        // 查询模型转疑点信息(多选)
        TurnSuspects: '/sjmx/queryModelMsgMulti'
      },
      rules: {
        proName: { required: true, message: '请选择项目名称', trigger: 'change' }
      },
      visible: false,
      treeDataSource: [],
      dataSource: [],
      treeLoading: false,
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 11,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] > 10
            ? range[0] - 1
            : range[0] + '-' + (range[1] > 10 ? range[1] - 1 : range[1]) + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      selectedRowKeys: [],
      selectedRows: [],
      treeRowKeys: [],
      expandedRowKeys: [],
      expandedRowKey: []
    }
  },
  watch: {
    $route: {
      handler: function(to) {
        if (Object.keys(to.query).length > 0) {
          // debugger
          let { selectedRowKeys, treeRowKeys, code, proName, proId, expandedRowKeys } = to.query
          this.queryParam = {
            code,
            proName,
            proId
          }
          this.selectedRowKeys = selectedRowKeys.split(',')
          this.treeRowKeys = treeRowKeys.split(',')
          this.expandedRowKeys = expandedRowKeys.split(',')
          this.$nextTick(() => {
            this.getTreeData()
            this.loadData(1)
          })
        } else if (Object.keys(to.params).length && to.params.from == 'sjxmss') {
          // let { projName, proId } = to.params
          // this.queryParam.proId = proId
          // this.queryParam.proName = projName
          // this.queryParam.extraId = proId
          // this.isBackButton = true
          // this.returnRecord = to.params.returnRecord
          // this.$nextTick(() => {
          //   // 这可能存在问题
          //   this.onSearch()
          // })
        }
      },
      immediate: true
    }
  },
  computed: {
    rowSelectionlist() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = [...selectedRowKeys]
          this.selectedRows = [...selectedRows]
        }
      }
    }
  },
  methods: {
    onSelectChange(selectedRowKeys, selectedRows) {
      let { subjectCode, pid } = selectedRows[0]
      this.expandedRowKey = [pid]
      this.treeRowKeys = selectedRowKeys
      this.queryParam.code = subjectCode
      this.selectedRowKeys = []
      this.selectedRows = []
      this.loadData(1)
    },
    renderEllipsis(text) {
      return <j-ellipsis length={10} value={text} />
    },
    searchReset() {
      this.queryParam = this.$options.data().queryParam
      this.treeDataSource = []
      this.dataSource = []
      this.selectedRowKeys = []
      this.selectedRows = []
      this.treeRowKeys = []
      this.expandedRowKey = []
      this.expandedRowKeys = []
    },
    onSearch() {
      this.getTreeData()
    },
    getTreeData() {
      this.treeLoading = true
      getAction(this.url.treelist, { ...this.queryParam }).then(res => {
        if (res.success) {
          this.treeDataSource = this.formatTreeData(res.result)
        } else {
          this.$message.warning(res.message)
        }
        this.treeLoading = false
      })
    },
    formatTreeData(data = []) {
      try {
        return data.map(item => {
          console.log(item)
          if (item.children.length > 0) {
            item.children = this.formatTreeData(item.children)
          } else {
            delete item.children
          }
          return item
        })
      } catch (error) {
        throw error
      }
    },
    updateQueryParam(data) {
      console.log('aaaaaaaaaaaaaa', data)
      // this.queryParam.extraId = data.proId
      this.queryParam.proId = data.proId
      this.queryParam.proName = data.proName
    },
    openOrganModel() {
      this.$refs.departModal.edit()
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams() //查询条件
      this.loading = true
      getAction(this.url.list, params).then(res => {
        if (res.success) {
          //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
           this.dataSource = res.result.records
          if (res.result.total) {
            this.ipagination.total = res.result.total
          } else {
            this.ipagination.total = 0
          }
          //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
        } else {
          this.$message.warning(res.message)
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    getQueryParams() {
      // 获取查询条件
      const sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      if (this.superParam) {
        var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters, this.superParam)
      } else {
        var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
      }
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize > 10 ? this.ipagination.pageSize - 1 : this.ipagination.pageSize
      return filterObj(param)
    },
    handleToYD() {
      if (this.dataSource.length) {
        const { startTime = '', endTime = '' } = this.queryParam
        // let ydnr = `中铁XX局XX项目未取得增值税劳务发票X亿元，设计税金X万元；X公司城际联络线`
        let param = Object.assign({}, this.queryParam, {
          selectedRowKeys: this.selectedRowKeys.join(','),
          treeRowKeys: this.treeRowKeys.join(','),
          expandedRowKeys: this.expandedRowKey.toString()
        })
        let ydnr = undefined
        let gzzd = undefined
        const time = `【${startTime}～${endTime}】【项目部超预算】`
        let ydList = JSON.stringify(this.selectedRows)
        this.ydLoading = true
        postAction(this.url.TurnSuspects, Object.assign({}, this.queryParam, this.superParam, { ydList: ydList })).then(
          res => {
            if (res.success) {
              if (res.result.length) {
                ydnr = res.result[0].ydms ? res.result[0].ydms : ydnr
                gzzd = res.result[0].gzzd ? res.result[0].gzzd : gzzd
              }
              this.addYdMulti(param, ydnr, time, gzzd)
            } else {
              this.$message.error(res.message)
            }
            if (res.code === 510) {
              this.$message.warning(res.message)
            }
            this.ydLoading = false
          }
        )
      } else {
        this.$message.error('空数据不能新建疑点')
      }
    },
    handleCheckDetail(record, index) {
      this.handleCheck(record, '凭证')
    },
    updateProList() {
      this.loadData(1)
    },
  }
}
</script>

<style lang="less">
.bgc_tooltip {
  .ant-tooltip-inner {
    // 这里是框框
    border-radius: 20px;
    color: #333;
    width: 400px;
    padding: 10px 15px;
    background-color: rgba(255, 255, 255, 0.274) !important;
  }
  .ant-tooltip-arrow::before {
    // 这里是小三角形
    background-color: #fff !important;
  }
}
</style>
<style lang="less" scoped>
@import '~@assets/less/tableTheme.less';

.img_css /deep/ .ant-card-body {
  padding: 15px 15px 0 15px;
}

.right-tree {
  max-height: 600px;
  overflow: auto;
}
</style>
